﻿//    <table id="commissions" class="EditContractScreenTable">
//        <thead>
//            <tr>
//                <th name="IntroducerName">Introducer</th>
//                <th name="CurrencyName">Currency</th>
//                <th name="Unit">Comm Unit</th>
//                <th name="Commission">Comm Value</th>
//                <th class="action"></th>
//            </tr>
//        </thead>
//
//        <tbody class="data">
//        </tbody>
//
//        <tr class="update" style="display: none">
//            <td key="IntroducerId">
//                @Html.DropDownList("MasterIntroducer", Model.IntroducersSelectList)
//            </td>
//            <td key="CurrencyId">
//                @Html.DropDownList("MasterCurrency", Model.CurrenciesSelectList)
//            </td>
//            <td key="UnitId">
//                @Html.DropDownList("MasterCommUnit", Model.CommissionUnitSelectList)
//            </td>
//            <td>
//                @{  string numberFormat = CTRMCommon.DataAnnotations.NumberFormatAttribute.Default;  }
//                @Html.TextBox("MasterCommissionValue", Model.CommissionValue.ToString(numberFormat))
//            </td>
//        </tr>
//        
//        <tr class="hidden" style="display: none">
//            <td>
//                <input type="hidden" name="commissions_data" value="@ViewBag.ContractCommissionsSourceNew" />
//            </td>
//        </tr>
//    </table>


$.fn.grid_rows = function (d) {
    if (d) { $('.hidden [type=hidden]', this).val(JSON.stringify(d)); return this; }
    return JSON.parse($('.hidden [type=hidden]', this).val());
}

$.fn.grid_render = function () {
    var g = $(this);
    var rows = g.grid_rows();

    var rows_html = '';

    $('tbody.data', g).empty();

    $.each(rows, function (i, r) {

        rows_html = '<tr>';

        $('thead th:not(.action)', g).each(function (i, n) {
            var ok = $(n).attr('name');
            rows_html += '<td name="' + ok + '" class="viewing">';
            rows_html += $(n).hasClass('bool') ?
                (r[ok] ? 'Yes' : 'No') :
                r[ok];
            rows_html += '</td>';
        });

        rows_html += '<td class="action">' +
                        '<img class="delete" src="images/delete_16x16.gif" /> <img class="edit" src="images/edit_16x16.gif" />' +
                        '<img class="save" src="images/save_16x16.gif" /> <img class="cancel" src="images/error_16x16.gif" />' +
                     '</td>';

        rows_html += '</tr>';

        $('tbody.data', g).append($(rows_html).data('datarow', r));
    });

    //$('thead', g)[rows.length == 0 ? 'hide' : 'show']();

    $('thead th[name]', g).each(function (i, n) {
        $('.update td:eq(' + i + ')', g).attr('name', $(n).attr('name'));
    });

    var act = $('.action', g);
    $('.delete, .edit', act).show();
    $('.save, .cancel', act).hide();

    var afterRenderFunc = g.find('tr.update:first').data('on_grid_rendered');
    if (afterRenderFunc) {
        afterRenderFunc(rows);
    }


    $('.edit', act).click(function () {
        var g = $(this).parents('table:first');
        var impove = g.find('tr.update:first').data('improve'); // event for 
        var row = $(this).parents('tr:first');
        if (impove) {
            impove(this, row.data('datarow'), edit);
        }
        else {
            edit(this, null);
        }

        function edit(target, additionalTd) {
            var g = $(target).parents('table:first');
            var upd = g.find('.update td').clone();
            var row = $(target).parents('tr:first');

            $('td:not(.action)', row).hide();

            if (additionalTd) {
                additionalTd.each(function (i, n) {
                    if ($(n).is("td") && $(n).attr('key')) {
                        upd.filter('[key="' + $(n).attr('key') + '"]').html($(n).html());
                    }
                });
            }

            upd.addClass('changing').each(function (i, n) {

                if ($(n).hasClass('bool')) {
                    $('input[type=checkbox]', n)[0].checked = row.data('datarow')[$(n).attr('name')];
                } else {
                    $('select, input', n).val(row.data('datarow')[$(n).attr('key') ? $(n).attr('key') : $(n).attr('name')]);
                }

                if ($(n).hasClass('readonly')) {
                    $('span', n).html(row.data('datarow')[$(n).attr('name')]);
                }

                if ($(n).hasClass('date')) {
                    var restrict = $(n).attr('restrict');
                    if (!restrict) { restrict = '' }

                    $('input', n).datepicker({
                        beforeShowDay: date.beforeShowDayArray(restrict.split(' ')),
                        beforeShow: function (input, inst) { $("#ui-datepicker-div").removeClass("hideDatePicker"); }
                    });

                    $('input', n).focus(function (e) {
                        $('input', n).datepicker("show");

                        button = $('input', n).datepicker('widget').find("button:contains('Done')");
                        button.click(function () {
                            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                            $('input', n).datepicker("setDate", new Date(year, month, 1, 0, 0, 0, 0));
                        });
                    });
                }
            });

            row.prepend(upd);

            $(target).parents('.action').find('img').toggle();
        }

    });

    $('.save', act).click(function () {
        var g = $(this).parents('table:first');
        var tr = $(this).parents('tr:first');
        var dr = tr.data('datarow');

        // validation
        try {

            $('td.changing', tr).each(function (i, n) {
                //check for empty
                if ($('input,select', n).val() == '') {
                    if ($(n).hasClass('null') || $('input,select', n).hasClass('null')) { return; }
                    alert($(n).attr('name') + ' is empty, should be entered'); throw 'Mes';
                }
                if ($(n).hasClass('float')) {
                    if (isNaN(Globalize.parseFloat($('input', n).val()))) {
                        alert($(n).attr('name') + ' should be number'); throw 'Mes';
                    }
                }
                if ($(n).hasClass('int')) {
                    if (parseInt($('input', n).val()).toString() != $('input', n).val()) {
                        alert($(n).attr('name') + ' should be integer'); throw 'Mes';
                    }
                }
                if ($(n).hasClass('date')) {
                    function isdate(d) {
                        try { $.datepicker.parseDate('dd-mm-yy', d) } catch (e) { return false; }
                        return true;
                    }
                    if (!isdate($('input', n).val())) {
                        alert($(n).attr('name') + ' should be date'); throw 'Mes';
                    }
                }
                if ($(n).hasClass('unique')) {
                    // check if this Id was used ever
                    var idtochk = $('select', n).val();

                    if ($.grep(g.grid_rows(), function (n, i) { return n.IntroducerId == idtochk && i != tr.index(); }).length > 0) {
                        alert($(n).attr('name') + ': "' + $('select :selected', n).text() + '" already used in a grid'); throw 'Mes';
                    }
                }
            });

        } catch (e) {
            return;
        }

        $('td.changing', tr).each(function (i, n) {

            if ($('select', n).length == 0 && $(n).attr('key') != undefined) {
                dr[$(n).attr('name')] = "";
                dr[$(n).attr('key')] = "";
                return;
            }

            if ($('select', n).length > 0) {
                dr[$(n).attr('name')] = $('select', n).val() == '' ? '' : $('select :selected', n).text();
                dr[$(n).attr('key')] = $('select', n).val();
            } else {
                if ($(n).hasClass('bool')) {
                    dr[$(n).attr('name')] = $('input:checked', n).length == 1;
                } else if ($(n).hasClass('readonly')) {
                    dr[$(n).attr('name')] = $('span', n).html();
                } else { 
                    dr[$(n).attr('name')] = $('input', n).val();
                }
            }
        });

        var rows = g.grid_rows();
        rows[tr.index()] = dr;

        g.grid_rows(rows).grid_render();
    });

    $('.cancel', act).click(function () {
        $(this).parents('table:first').grid_render();
    });

    $('.delete', act).click(function () {
        var g = $(this).parents('table:first');
        var tr = $(this).parents('tr:first');

        var rows = g.grid_rows();
        rows.splice(tr.index(), 1);

        g.grid_rows(rows).grid_render();
    });
}

$.fn.grid = function () {
    return this.each(function (i, g) {
        $(g).grid_render();
    });
}